package models.wifi


import java.sql.Timestamp
import java.time.LocalDateTime

import javax.inject.Inject
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import play.db.NamedDatabase
import slick.jdbc.JdbcProfile

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, ExecutionContext, Future}

case class WiFiInfo(name: String, password: String, note: Option[String]=None, online:Boolean=false,date: Timestamp=Timestamp.valueOf(LocalDateTime.now()))

class WifiInfoRepository @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext)
  extends HasDatabaseConfigProvider[JdbcProfile] {
  //  private val dbConfig = dbConfigProvider.get[JdbcProfile]

  import dbConfig._
  import profile.api._

  private class WiFiInfoTable(tag: Tag) extends Table[WiFiInfo](tag, "Public_WifiInfo".toUpperCase) {

    def name = column[String]("name".toUpperCase, O.PrimaryKey)

    def password = column[String]("password".toUpperCase)

    def date = column[Timestamp]("date".toUpperCase)

    def note = column[Option[String]]("note".toUpperCase)

    def online = column[Boolean]("online".toUpperCase)

    def * = (name, password, note, online,date).<>((WiFiInfo.apply _).tupled, WiFiInfo.unapply)
  }

  private val wifi = TableQuery[WiFiInfoTable]

  def list: Future[Seq[WiFiInfo]] = db.run {
    wifi.result
  }

  def online: Future[Seq[WiFiInfo]] = db.run {
    wifi.filter(_.online===true).result
  }

  def findByKey(key: String) = {
    //    val a = kvTable.filter(_.kvKey===key)
    val a = for (c <- wifi if c.name === key) yield c
    db.run(a.result)
  }

  def insert(wiFiInfo: WiFiInfo) = db.run {
    (wifi returning wifi.map(_.name)) += wiFiInfo
  }

  def update(wiFiInfo: WiFiInfo) = db.run {
    wifi.filter(_.name === wiFiInfo.name).map(f => f).update(wiFiInfo)
  }

  def insertOrUpdate(wiFiInfo: WiFiInfo) = {
    db.run(wifi.filter(_.name === wiFiInfo.name).result).flatMap { f =>
      if (f.nonEmpty) update(wiFiInfo)
      else insert(wiFiInfo)
    }
  }

  def delete(name:String)= db.run(wifi.filter(_.name === name).delete)

}

